<?php

namespace app\api\controller;

use addons\mycurrency\library\Poster;
use addons\mycurrency\library\ThirdLogin;
use app\admin\model\Area;
use app\common\controller\Api;
use app\common\library\device\cabinet\Analysis;
use app\common\library\device\cabinet\Control;
use app\common\library\device\cabinet\Logic;
use app\common\model\mycurrency\Device;
use app\common\model\mycurrency\DeviceInstruction;
use app\common\model\mycurrency\LeaseDeposit;
use app\common\model\mycurrency\LeaseOrder;
use app\common\model\mycurrency\MerchantMoneyLog;
use app\common\model\mycurrency\MerchantMoneyWithdrawal;
use app\common\model\mycurrency\OperateDistributionUser;
use app\common\mqtt\MqttPublisher;
use think\Db;
//use think\Exception;
use Kkokk\Poster\PosterManager;
use think\Exception;
use Yansongda\Pay\Exceptions\GatewayException;
use alipay\aop\AopCertClient;
use app\common\library\AlipayFundService;


/**
 * 示例接口
 */
class Demo extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function lixian()
    {
        trace('========================收到设备离线通知==============================');
        $param = $this->request->param();
        trace([$param]);
    }

    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功'
        })
     */
    public function test()
    {

//        hook('handelWechatPayScoreCancel', ['order_id' => 3736]);
//        die();
//        $data = DeviceInstruction::where([
//            'device_id' => 117,
////            'code' => ['<>',105],
//            'code' => 22,
//            'device_lattice_id' => 705
//        ])->select();
//        foreach($data as $k => $v){
//            $data[$k]['createtime'] = date('Y-m-d H:i:s',$data[$k]['createtime']);
//        }
//        $this->success('',$data);
//        LeaseOrder::orderDivideinto('726');
//        die();
//        $aop = new AopCertClient();
//        $alipayCertPath="/www/wwwroot/billiards/addons/epay/certs/alipayCertPublicKey.crt";
//        //调用getPublicKey获取支付宝公钥
//        $alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
//        //输出
//        echo '支付宝公钥证书值'.$alipayrsaPublicKey;
//        die();
//        //执行取消免押操作
//        hook('handelWechatPayScoreCancel', ['order_id' => 1783]);
//        die();
//        LeaseOrder::orderEnd(68,'1741164208');
//        die();
//
//        OperateDistributionUser::poster(334);
//        die;
//        Db::startTrans();
//        try {
//            LeaseDeposit::depositRefund(189);
//            Db::commit();
//        } catch (Exception $e) {
//            Db::rollback();
//            $this->error($e->getMessage());
//        }
//        die();

//        $lease_time = '1730796468';
//        $return_time = '1730796499';
//        $lease_duration =ceil(bcdiv(
//            bcsub(
//                $return_time,//结束租赁时间
//                $lease_time//开始租赁时间
//            ),
//            60,
//            4
//        ));//开始租赁时间 - 结束租赁时间 / 60 = 租赁时长 分钟
//        die('==' . $lease_duration);
//        Db::startTrans();
//        try {
//            ThirdLogin::bindingPhone(19,'13900000001');
//            Db::commit();
//        } catch (Exception $e) {
//            Db::rollback();
//            $this->error($e->getMessage());
//        }
//
//        die();
        //押金退款
//        Db::startTrans();
//        try {
//            LeaseDeposit::depositRefund(165);
//            die('123');
//            Db::commit();
//        } catch (Exception|GatewayException $e) {
//            Db::rollback();
//            $this->error($e->getMessage());
//        }

        //发送给设备
//        $deviceId = '861459078832512';
//        //$str = ['c' => 22, 'f' => "TAIQIU001", 't' => "861459072204833", 'm' => "32,2&1", 's' => "1", 'mi' => 101,];//开门
//        $str = ['c' => 24, 'f' => "TAIQIU001", 't' => "861459078832512", 'm' => "0", 's' => "1", 'mi' => 23,];//查询柜门状态
//        //$str = ['c' => 100, 'f' => "TAIQIU001", 't' => "861459072204833", 'm' => "0", 's' => "1", 'mi' => 26,];//查询网络
//        //$str = ['c' => 108, 'f' => "TAIQIU001", 't' => "861459072204833", 'm' => "6&1&0", 's' => "1", 'mi' => 28,];//开关灯
//        //$str = ['c' => 50, 'f' => "TAIQIU001", 't' => "861459078832355", 'm' => "0", 's' => "1", 'mi' => 25,];//传感器状态查询
//        $str = ['c' => 104, 'f' => "TAIQIU001", 't' => "869100079726855", 'm' => "120", 's' => "1", 'mi' => 2000,];//读卡
//        $device = Device::where(['is_online' => Device::IS_ONLINE_ZAIXIAN,'deletetime' => null])->select();
//        foreach($device as $k => $v){
//            $data = "120";
//            Control::sending($v['id'],Analysis::CODE_XINTIAO_PEIZHI,$data,[]);
//        }
//        die();


//        $mqtt_publisher = new MqttPublisher();
//        $mqtt_publisher->publishMessage($deviceId,$str);
//        die();

        //设备上线
        //$message = '{"c":102,"f":"865373043994156","t":"CQAZ01","m":"31&20241018105612123456&5G&GT7C2400","s":"1","mi":"2"}';
        //设备离线
        //$message = '{"c":103,"f":"865373043994156","t":"CQAZ01","m":"31&20241018105612123456&5G&GT7C2400","s":"1","mi":"3"}';

        //开门指令发送到设备应答
//        $message = '{
//	"c":	21,
//	"f":	"861459072204817",
//	"t":	"TAIQIU001",
//	"m":	"32,2&1",
//	"s":	"1",
//	"mi":	39
//}';
        //开门执行结果
//        $message = '{
//	"c":	23,
//	"f":	"861459072204817",
//	"t":	"TAIQIU001",
//	"m":	"0,2&1",
//	"s":	"1",
//	"mi":	62
//}';
        //柜门状态
        $message = '{
	"c":	23,
	"f":	"861459072204908",
	"t":	"TAIQIU001",
	"m":	"0,2&1",
	"s":	"1",
	"mi":	1719
}';
        //查询柜门状体应答
//        $message = '{
//            "c":	25,
//            "f":	"861459072204817",
//            "t":	"TAIQIU001",
//            "m":	"2",
//            "s":	"1",
//            "mi":	39
//        }';

        //传感器状态应答
//        $message = '{
//            "c":	51,
//            "f":	"861459078832355",
//            "t":	"TAIQIU001",
//            "m":	"1&1&1&1&1&1&1&1",
//            "s":	"1",
//            "mi":	25
//        }';

        //查询柜门状态
//        $message = '{
//            "c":	25,
//            "f":	"861459078832512",
//            "t":	"TAIQIU001",
//            "m":	"1&1&1&1&1&1&2&2&2&2&2&2&2&2&2&2",
//            "s":	"1",
//            "mi":	23
//        }';

        LeaseOrder::orderStartRenting(5439);
        die();
        //卡ID应答
        $message = '{
	"c":	111,
	"f":	"861459072204387",
	"t":	"TAIQIU001",
	"m":	"E0040150E3C926E3",
	"s":	"1",
	"mi":	138
}';

        $data = Analysis::analysis($message);
        Logic::index('TAIQIU001',$data);
//        print_r($data);
//        $data = Analysis::sendingAssemble(22,1,[32,10,1]);
//        print_r($data);
        die();
        $this->success('返回成功', $this->request->param());
    }

    /**
     * 无需登录的接口
     *
     */
    public function test1()
    {
        $this->success('返回成功', ['action' => 'test1']);
    }

    /**
     * 需要登录的接口
     *
     */
    public function test2()
    {
        $this->success('返回成功', ['action' => 'test2']);
    }

    /**
     * 需要登录且需要验证有相应组的权限
     *
     */
    public function test3()
    {
        $this->success('返回成功', ['action' => 'test3']);
    }



    /**
     * 测试不同单价的台球杆租赁订单
     *
     * @ApiTitle    (测试不同单价台球杆租赁)
     * @ApiSummary  (测试创建不同单价的台球杆租赁订单)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/demo/testDifferentRates)
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="测试完成")
     * @ApiReturnParams   (name="data", type="array", description="不同单价的测试结果")
     */
    public function test4()
    {
        try {
            // 生成唯一的订单号
            $outOrderNo = 'mianya' . time()  . rand(100000, 999999);
            $outOrderNo = 80777352559380251;
            // 直接调用 createOrder 方法创建芝麻免押订单
            $orderStr = AlipayFundService::createOrder(
                '台球杆租赁芝麻免押授权',    // 订单标题
                $outOrderNo,                // 商户订单号
                null,                       // 商户请求流水号（使用默认）
                0.05,                       // 冻结金额（1分钱用于测试）
                0.01,                       // 每小时租赁单价
                '台球杆租赁'                // 租赁项目名称
            );

            // 检查 orderStr 是否生成成功
            if (empty($orderStr)) {
                $this->error('生成授权订单失败，orderStr 为空');
            }

            // 记录日志用于调试
            trace('生成的 orderStr: ' . substr($orderStr, 0, 200) . '...');
            trace('orderStr 长度: ' . strlen($orderStr));

          

        } catch (\Exception $e) {
            trace('test4 异常: ' . $e->getMessage());
            trace('异常堆栈: ' . $e->getTraceAsString());
            $this->error('生成授权订单失败: ' . $e->getMessage());
        }
          $this->success('获取授权订单成功', $orderStr);
    }

    /**
     * 测试支付宝资金授权撤销接口
     *
     * @ApiTitle    (测试支付宝资金授权撤销)
     * @ApiSummary  (测试撤销支付宝资金授权订单，用于硬件故障等无法提供服务的情况)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/demo/test5)
     * @ApiParams   (name="out_request_no", type="string", required=false, description="商户请求流水号")
     * @ApiParams   (name="out_order_no", type="string", required=false, description="商户订单号")
     * @ApiParams   (name="remark", type="string", required=false, description="撤销原因")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="撤销成功")
     * @ApiReturnParams   (name="data", type="object", description="撤销结果数据")
     */
    public function test5()
    {

            // 获取请求参数，如果没有传入则使用测试数据
            $outRequestNo = $this->request->param('out_request_no', '80777352559380242');
            $outOrderNo = $this->request->param('out_order_no', '80777352559380242');
            $remark = $this->request->param('remark', '硬件故障，无法提供服务，撤销授权');



            // 调用撤销接口
            $result = AlipayFundService::cancelAuthOrder($remark, $outRequestNo, $outOrderNo);

            // 记录撤销结果
            trace('test5 撤销结果');
            trace($result);

            if ($result['success']) {
                // 撤销成功
                $this->success('资金授权撤销成功', [
                    'cancel_result' => $result,
                    'test_params' => [
                        'remark' => $remark,
                        'out_request_no' => $outRequestNo,
                        'out_order_no' => $outOrderNo
                    ]
                ]);
            } else {
                // 撤销失败，但不抛出异常，返回失败信息
                $this->error('资金授权撤销失败: ' . ($result['msg'] ?? '未知错误'), [
                    'cancel_result' => $result,
                    'test_params' => [
                        'remark' => $remark,
                        'out_request_no' => $outRequestNo,
                        'out_order_no' => $outOrderNo
                    ],
                    'error_details' => [
                        'code' => $result['code'] ?? '',
                        'sub_code' => $result['sub_code'] ?? '',
                        'sub_msg' => $result['sub_msg'] ?? ''
                    ]
                ]);
            }


    }

    /**
     * 测试支付宝资金授权操作详情查询接口
     *
     * @ApiTitle    (测试支付宝资金授权详情查询)
     * @ApiSummary  (测试查询支付宝资金授权操作的详细信息，包括冻结、解冻、支付等操作状态)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/demo/test6)
     * @ApiParams   (name="out_request_no", type="string", required=false, description="商户请求流水号")
     * @ApiParams   (name="out_order_no", type="string", required=false, description="商户订单号")
     * @ApiParams   (name="operation_type", type="string", required=false, description="操作类型: FREEZE-冻结, UNFREEZE-解冻, PAY-支付")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="查询成功")
     * @ApiReturnParams   (name="data", type="object", description="查询结果详细数据")
     */
    public function test6()
    {

            // 获取请求参数
            $outRequestNo = $this->request->param('out_request_no', '80777352559380241');
            $outOrderNo = $this->request->param('out_order_no', '80777352559380241');
            $operationType = $this->request->param('operation_type', 'FREEZE');

            // 调用查询接口
            $result = AlipayFundService::queryAuthOrderDetail($outOrderNo, $outRequestNo, $operationType);

            // 记录查询结果
            trace('test6 查询结果: ');
            trace($result);

            if ($result['code']==10000) {
                // 查询成功
                $this->success('资金授权详情查询成功', [
                    'query_result' => $result,
                    'test_params' => [
                        'out_request_no' => $outRequestNo,
                        'out_order_no' => $outOrderNo,
                        'operation_type' => $operationType
                    ],
                    'data_summary' => [
                        '授权订单号' => $result['data']['auth_no'] ?? 'N/A',
                        '订单状态' => $result['data']['order_status'] ?? 'N/A',
                        '操作类型' => $result['data']['operation_type'] ?? 'N/A',
                        '操作状态' => $result['data']['status'] ?? 'N/A',
                        '冻结总金额' => $result['data']['total_freeze_amount'] ?? '0.00',
                        '剩余金额' => $result['data']['rest_amount'] ?? '0.00',
                        '支付总金额' => $result['data']['total_pay_amount'] ?? '0.00',
                        '创建时间' => $result['data']['gmt_create'] ?? 'N/A',
                        '交易时间' => $result['data']['gmt_trans'] ?? 'N/A'
                    ]
                ]);
            } else {
                // 查询失败，但不抛出异常，返回失败信息
                $this->error('资金授权详情查询失败: ' . ($result['msg'] ?? '未知错误'), [
                    'query_result' => $result,
                    'test_params' => [
                        'out_request_no' => $outRequestNo,
                        'out_order_no' => $outOrderNo,
                        'operation_type' => $operationType
                    ],
                    'error_details' => [
                        'code' => $result['code'] ?? '',
                        'sub_code' => $result['sub_code'] ?? '',
                        'sub_msg' => $result['sub_msg'] ?? ''
                    ],
                    'common_errors' => [
                        'ACQ.TRADE_NOT_EXIST' => '交易不存在，请检查订单号或请求流水号是否正确',
                        'INVALID_PARAMETER' => '参数无效，请检查传入的参数格式',
                        'SYSTEM_ERROR' => '系统错误，请稍后重试'
                    ]
                ]);
            }
    }

    /**
     * 测试支付宝资金授权解冻接口
     *
     * @ApiTitle    (测试支付宝资金授权解冻)
     * @ApiSummary  (测试解冻支付宝资金授权订单中的部分或全部金额)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/demo/test7)
     * @ApiParams   (name="auth_no", type="string", required=false, description="支付宝资金授权订单号")
     * @ApiParams   (name="out_request_no", type="string", required=false, description="解冻请求流水号")
     * @ApiParams   (name="amount", type="number", required=false, description="解冻金额")
     * @ApiParams   (name="remark", type="string", required=false, description="解冻原因")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="解冻成功")
     * @ApiReturnParams   (name="data", type="object", description="解冻结果数据")
     */
    public function test7()
    {

            // 获取请求参数
            $authNo = $this->request->param('auth_no', '2025061410002001770576261583');
            $outRequestNo = $this->request->param('out_request_no', '80777352559380255'); //这个随便编一个都没问题
            $amount = $this->request->param('amount', '0.03');
            $remark = $this->request->param('remark', 'hello');
            // 参数类型转换和验证
            $amount = floatval($amount);
            if ($amount <= 0) {
                $this->error('解冻金额必须大于0', [
                    'current_amount' => $amount,
                    'valid_range' => '[0.01, 100000000.00]'
                ]);
            }

            // 调用解冻接口
            $result = AlipayFundService::unfreezeAuthOrder($authNo, $outRequestNo, $amount, $remark);

            // 记录解冻结果
            trace('test7 解冻结果: ');
            trace($result);

            if ($result['success']) {
                // 解冻成功
                $this->success('资金授权解冻成功', [
                    'unfreeze_result' => $result,
                    'test_params' => [
                        'auth_no' => $authNo,
                        'out_request_no' => $outRequestNo,
                        'amount' => $amount,
                        'remark' => $remark
                    ],
                    'operation_summary' => [
                        '授权订单号' => $result['data']['auth_no'] ?? 'N/A',
                        '商户订单号' => $result['data']['out_order_no'] ?? 'N/A',
                        '操作流水号' => $result['data']['operation_id'] ?? 'N/A',
                        '解冻请求号' => $result['data']['out_request_no'] ?? 'N/A',
                        '解冻金额' => $result['data']['amount'] ?? '0.00',
                        '操作状态' => $result['data']['status'] ?? 'N/A',
                        '交易时间' => $result['data']['gmt_trans'] ?? 'N/A',
                        '信用金额' => $result['data']['credit_amount'] ?? '0.00',
                        '资金金额' => $result['data']['fund_amount'] ?? '0.00'
                    ],
                    'next_steps' => [
                        '1. 可以通过 test6 查询解冻操作详情',
                        '2. 使用 operation_type=UNFREEZE 查询解冻记录',
                        '3. 检查订单剩余冻结金额是否正确'
                    ]
                ]);
            } else {
                // 解冻失败
                $this->error('资金授权解冻失败: ' . ($result['msg'] ?? '未知错误'), [
                    'unfreeze_result' => $result,
                    'test_params' => [
                        'auth_no' => $authNo,
                        'out_request_no' => $outRequestNo,
                        'amount' => $amount,
                        'remark' => $remark
                    ],
                    'error_details' => [
                        'code' => $result['code'] ?? '',
                        'sub_code' => $result['sub_code'] ?? '',
                        'sub_msg' => $result['sub_msg'] ?? ''
                    ],
                    'common_errors' => [
                        'ACQ.TRADE_NOT_EXIST' => '授权订单不存在，请检查 auth_no 是否正确',
                        'ACQ.TRADE_STATUS_ERROR' => '订单状态不正确，可能已经全部解冻或撤销',
                        'INVALID_PARAMETER' => '参数无效，请检查金额格式和范围',
                        'ACQ.AMOUNT_NOT_ENOUGH' => '解冻金额超过剩余冻结金额',
                        'ACQ.REPEAT_REQUEST' => '重复的解冻请求，请检查 out_request_no'
                    ],
                    'troubleshooting' => [
                        '1. 使用 test6 查询授权订单当前状态和剩余金额',
                        '2. 确保 auth_no 是有效的授权订单号',
                        '3. 确保解冻金额不超过剩余冻结金额',
                        '4. 确保 out_request_no 在同一授权单下是唯一的'
                    ]
                ]);
            }


    }

    /**
     * 测试支付宝统一收单交易支付接口（预授权转支付/扣款）
     *
     * @ApiTitle    (测试支付宝预授权转支付)
     * @ApiSummary  (测试使用授权单号对用户已授权金额发起扣款，用于用户享受服务后的费用结算)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/demo/test8)
     * @ApiParams   (name="out_trade_no", type="string", required=false, description="商户订单号")
     * @ApiParams   (name="total_amount", type="number", required=false, description="扣款金额")
     * @ApiParams   (name="subject", type="string", required=false, description="订单标题")
     * @ApiParams   (name="auth_no", type="string", required=false, description="资金预授权单号")
     * @ApiParams   (name="auth_confirm_mode", type="string", required=false, description="预授权确认模式: COMPLETE或NOT_COMPLETE")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="扣款成功")
     * @ApiReturnParams   (name="data", type="object", description="扣款结果数据")
     */
    public function test8()
    {

            // 获取请求参数
            $outTradeNo = $this->request->param('out_trade_no', 'PAY_' . '2025061410002001770576261583');
            $totalAmount = $this->request->param('total_amount', '0.02');
            $subject = $this->request->param('subject', '台球杆租赁费用');
            $authNo = $this->request->param('auth_no', '2025061410002001770576261583');
            $authConfirmMode = $this->request->param('auth_confirm_mode', 'COMPLETE');

            // 参数类型转换和验证
            $totalAmount = floatval($totalAmount);
            if ($totalAmount <= 0) {
                $this->error('扣款金额必须大于0', [
                    'current_amount' => $totalAmount,
                    'valid_range' => '[0.04, 100000000]'
                ]);
            }

            // 验证预授权确认模式
            if (!in_array($authConfirmMode, ['COMPLETE', 'NOT_COMPLETE'])) {
                $this->error('无效的预授权确认模式', [
                    'current_mode' => $authConfirmMode,
                    'valid_modes' => ['COMPLETE', 'NOT_COMPLETE'],
                    'mode_description' => [
                        'COMPLETE' => '转交易完成后解冻剩余冻结金额',
                        'NOT_COMPLETE' => '转交易完成后不解冻剩余冻结金额'
                    ]
                ]);
            }


            // 调用扣款接口
            $result = AlipayFundService::payWithAuth($outTradeNo, $totalAmount, $subject, $authNo, 'PREAUTH_PAY', $authConfirmMode);

            // 记录扣款结果
            trace('test8 扣款结果: ');
            trace($result);

            if ($result['success']) {
                // 扣款成功
                $this->success('预授权转支付成功', [
                    'pay_result' => $result,
                    'test_params' => [
                        'out_trade_no' => $outTradeNo,
                        'total_amount' => $totalAmount,
                        'subject' => $subject,
                        'auth_no' => $authNo,
                        'auth_confirm_mode' => $authConfirmMode
                    ],
                    'transaction_summary' => [
                        '支付宝交易号' => $result['data']['trade_no'] ?? 'N/A',
                        '商户订单号' => $result['data']['out_trade_no'] ?? 'N/A',
                        '交易总金额' => $result['data']['total_amount'] ?? '0.00',
                        '实收金额' => $result['data']['receipt_amount'] ?? '0.00',
                        '买家实付金额' => $result['data']['buyer_pay_amount'] ?? '0.00',
                        '付款时间' => $result['data']['gmt_payment'] ?? 'N/A',
                        '买家账号' => $result['data']['buyer_logon_id'] ?? 'N/A',
                        '预授权支付模式' => $result['data']['auth_trade_pay_mode'] ?? 'N/A',
                        '异步支付模式' => $result['data']['async_payment_mode'] ?? 'N/A',
                        '积分支付金额' => $result['data']['point_amount'] ?? '0.00',
                        '平台优惠金额' => $result['data']['discount_amount'] ?? '0.00',
                        '商家优惠金额' => $result['data']['mdiscount_amount'] ?? '0.00'
                    ],
                    'fund_details' => $result['data']['fund_bill_list'] ?? [],
                    'voucher_details' => $result['data']['voucher_detail_list'] ?? [],
                    'next_steps' => [
                        '1. 保存支付宝交易号用于后续对账和退款',
                        '2. 更新订单状态为已支付',
                        '3. 如果使用 COMPLETE 模式，剩余金额已自动解冻',
                        '4. 可以通过 test6 查询授权订单最新状态'
                    ],
                    'business_tips' => [
                        '扣款成功表示用户已被收费',
                        '请及时更新订单状态和用户账户',
                        '如需退款请使用支付宝退款接口',
                        '建议记录交易流水用于财务对账'
                    ]
                ]);
            } else {
                // 扣款失败
                $this->error('预授权转支付失败: ' . ($result['msg'] ?? '未知错误'), [
                    'pay_result' => $result,
                    'test_params' => [
                        'out_trade_no' => $outTradeNo,
                        'total_amount' => $totalAmount,
                        'subject' => $subject,
                        'auth_no' => $authNo,
                        'auth_confirm_mode' => $authConfirmMode
                    ],
                    'error_details' => [
                        'code' => $result['code'] ?? '',
                        'sub_code' => $result['sub_code'] ?? '',
                        'sub_msg' => $result['sub_msg'] ?? ''
                    ],
                    'common_errors' => [
                        'ACQ.TRADE_NOT_EXIST' => '授权订单不存在，请检查 auth_no 是否正确',
                        'ACQ.TRADE_STATUS_ERROR' => '授权订单状态不正确，可能已撤销或过期',
                        'INVALID_PARAMETER' => '参数无效，请检查订单号格式和金额范围',
                        'ACQ.AMOUNT_NOT_ENOUGH' => '扣款金额超过授权冻结金额',
                        'ACQ.REPEAT_REQUEST' => '重复的支付请求，请检查 out_trade_no',
                        'ACQ.AUTH_CODE_INVALID' => '授权码无效或已过期'
                    ],
                    'troubleshooting' => [
                        '1. 使用 test6 查询授权订单当前状态和可用金额',
                        '2. 确保 auth_no 是有效且未撤销的授权订单号',
                        '3. 确保扣款金额不超过授权冻结金额',
                        '4. 确保 out_trade_no 在商户端是唯一的',
                        '5. 检查授权订单是否已过期'
                    ]
                ]);
            }


    }

    /**
     * 测试支付宝统一收单交易查询接口
     *
     * @ApiTitle    (测试支付宝交易查询)
     * @ApiSummary  (测试查询支付宝支付订单状态，用于确认交易状态和完成业务逻辑)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/demo/test9)
     * @ApiParams   (name="out_trade_no", type="string", required=false, description="商户订单号")
     * @ApiParams   (name="trade_no", type="string", required=false, description="支付宝交易号")
     * @ApiParams   (name="query_options", type="string", required=false, description="查询选项，多个用逗号分隔: trade_settle_info,fund_bill_list,voucher_detail_list")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="查询成功")
     * @ApiReturnParams   (name="data", type="object", description="交易查询结果数据")
     */
    public function test9()
    {

            // 获取请求参数
            $outTradeNo = $this->request->param('out_trade_no', 'PAY_' . '2025061410002001770576261583');
            // 调用交易查询接口
            $result = AlipayFundService::queryTrade($outTradeNo);

            // 记录查询结果
            trace('test9 交易查询结果: ');
            trace($result);

            if ($result['success']) {
                // 查询成功
                $this->success('交易查询成功', [
                    'query_result' => $result,
                    'test_params' => [
                        'out_trade_no' => $outTradeNo,
                    ],
                    'transaction_summary' => [
                        '商户订单号' => $result['data']['out_trade_no'] ?? 'N/A',
                        '交易状态' => $result['data']['trade_status'] ?? 'N/A',
                        '交易总金额' => $result['data']['total_amount'] ?? '0.00',
                        '实收金额' => $result['data']['receipt_amount'] ?? '0.00',
                        '买家实付金额' => $result['data']['buyer_pay_amount'] ?? '0.00',
                        '买家账号' => $result['data']['buyer_logon_id'] ?? 'N/A',
                        '创建时间' => $result['data']['gmt_create'] ?? 'N/A',
                        '付款时间' => $result['data']['gmt_payment'] ?? 'N/A',
                        '结算时间' => $result['data']['gmt_settlement'] ?? 'N/A',
                        '订单标题' => $result['data']['subject'] ?? 'N/A',
                        '预授权支付模式' => $result['data']['auth_trade_pay_mode'] ?? 'N/A'
                    ],
                    'trade_status_explanation' => [
                        'WAIT_BUYER_PAY' => '交易创建，等待买家付款',
                        'TRADE_CLOSED' => '未付款交易超时关闭，或支付完成后全额退款',
                        'TRADE_SUCCESS' => '交易支付成功',
                        'TRADE_FINISHED' => '交易结束，不可退款'
                    ],
                    'extended_info' => [
                        '资金渠道信息' => !empty($result['data']['fund_bill_list']) ? '已返回' : '未请求',
                        '优惠券信息' => !empty($result['data']['voucher_detail_list']) ? '已返回' : '未请求',
                        '结算信息' => !empty($result['data']['trade_settle_info']) ? '已返回' : '未请求'
                    ]
                ]);
            } else {
                // 查询失败
                $this->error('交易查询失败: ' . ($result['msg'] ?? '未知错误'), [
                    'query_result' => $result,
                    'test_params' => [
                        'out_trade_no' => $outTradeNo,
                    ],
                    'error_details' => [
                        'code' => $result['code'] ?? '',
                        'sub_code' => $result['sub_code'] ?? '',
                        'sub_msg' => $result['sub_msg'] ?? ''
                    ],
                    'common_errors' => [
                        'ACQ.TRADE_NOT_EXIST' => '交易不存在，请检查订单号或交易号是否正确',
                        'INVALID_PARAMETER' => '参数无效，请检查传入的参数格式',
                        'SYSTEM_ERROR' => '系统错误，请稍后重试',
                        'ACQ.SYSTEM_ERROR' => '系统繁忙，请稍后重试'
                    ],
                    'troubleshooting' => [
                        '1. 确保传入的订单号或交易号是正确的',
                        '2. 检查订单是否确实存在于支付宝系统中',
                        '3. 如果是刚创建的订单，可能需要等待几秒钟再查询',
                        '4. 确保查询选项参数格式正确'
                    ]
                ]);
            }


    }

}
